<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="排序" prop="asc">
        <el-radio-group v-model="queryParams.asc" @change="handleQuery">
          <el-radio label="asc" value="asc">顺序</el-radio>
          <el-radio label="desc" value="desc">倒序</el-radio>
        </el-radio-group>

      </el-form-item>
      <el-form-item label="排序依据" prop="orderByName">
        <el-radio-group v-model="queryParams.orderByName" @change="handleQuery">
          <el-radio label="attendNum" value="attendNum">参与次数</el-radio>
          <el-radio label="c" value="c">权益次数</el-radio>
          <el-radio label="id" value="id">主键</el-radio>
        </el-radio-group>

      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['ypp:user:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['ypp:user:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ypp:user:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ypp:user:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleUpdate"
          :disabled="single"
          v-hasPermi="['ypp:user:update']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          v-hasPermi="['ypp:user:remove']"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="参与次数" align="center" prop="attendNum" >
        <template slot-scope="scope">
          <span style="cursor: pointer;color: #0000ff;" @click="showEnrolls(scope.row)">
            {{ scope.row.attendNum }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="权益次数" align="center" prop="c"/>
      <el-table-column label="生日" align="center" prop="birthday" width="100px"/>
      <el-table-column label="性别" align="center" prop="gender" :formatter="genderFormat"/>
      <el-table-column label="证件类型" align="center" prop="idType" :formatter="cardFormat"/>
      <el-table-column label="身份证号" align="center" prop="identityNumber"/>
      <el-table-column label="学校" align="center" prop="school" />
      <el-table-column label="班级" align="center" prop="grade" />
      <el-table-column label="监护人电话" align="center" prop="phone" width="120px"/>
      <el-table-column label="紧急联系电话" align="center" prop="emergencyPhone"  width="120px"/>
      <el-table-column label="性格特点" align="center" prop="personality" />
      <el-table-column label="地区" align="center" prop="region" />
      <el-table-column label="所属账号" align="center" prop="account"  width="120px"/>
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     v-hasPermi="['wx:coupon:add']"
                     icon="el-icon-view" @click="sendCoupon(scope.row)">发放优惠券</el-button>
          <el-button size="mini"
                     type="text"
                     v-hasPermi="['wx:qyk:add']"
                     icon="el-icon-view" @click="sendCard(scope.row)">添加权益卡</el-button>
          <el-button size="mini"
                     type="text"
                     v-hasPermi="['ypp:couponDetail:list']"
                     icon="el-icon-view" @click="checkCoupon(scope.row)">查看优惠券</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination

      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改活动报名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" placeholder="请选择年龄"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男" value="1"></el-radio>
            <el-radio label="女" value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="form.grade" placeholder="请选择年级">
            <el-option label="一年级" value="一年级"></el-option>
            <el-option label="二年级" value="二年级"></el-option>
            <el-option label="三年级" value="三年级"></el-option>
            <el-option label="四年级" value="四年级"></el-option>
            <el-option label="五年级" value="五年级"></el-option>
            <el-option label="六年级" value="六年级"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="identityNumber">
          <el-input v-model="form.identityNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="学校" prop="school">
          <el-input v-model="form.school" placeholder="请输入学校" />
        </el-form-item>
        <el-form-item label="所属账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="地区">
          <el-input v-model="form.region" placeholder="请选择地区">
          </el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请选择地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发优惠券" :visible.sync="couponShow" v-if="couponShow" width="400px" append-to-body>
      <el-form  ref="couponForm" :model="couponForm"  label-width="80px">
        <el-form-item label="优惠券" prop="name">
          <el-select v-model="couponForm.couponId"  placeholder="请选择优惠券">
            <el-option v-for="(item,index) in couponInfoList" :disabled="item.disabled" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitCouponForm">提交</el-button>
        <el-button @click="couponShow = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发权益卡" :visible.sync="cardShow" v-if="cardShow" width="400px" append-to-body>
      <el-form  ref="couponForm" :model="cardForm"  label-width="80px">
        <el-form-item label="权益卡" prop="qykId">
          <el-select v-model="cardForm.qykId"  placeholder="请选择权益卡">
            <el-option v-for="(item,index) in qykList" :disabled="item.disabled" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权益次数" prop="count">
          <el-input-number v-model="cardForm.count"  placeholder="请输入权益次数"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitCardForm">提交</el-button>
        <el-button @click="cardShow = false">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog title="活动记录" :visible.sync="enrollShow" v-if="enrollShow" width="1200px" append-to-body>
      <el-table :data="attendList">
        <el-table-column label="订单编号" align="center" prop="id" />
        <el-table-column label="活动名称" align="center" prop="activityName" width="150px">
        </el-table-column>
        <el-table-column label="档期" align="center" prop="generationName" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column  label="性别" align="center" prop="gender">
          <template slot-scope="scope">
            <span v-if="scope.row.gender == 1">男</span>
            <span v-else-if="scope.row.gender == 2">女</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="监护人电话" align="center" prop="phone" :show-overflow-tooltip="true"/>
        <el-table-column label="报名时间" align="center" prop ="createTime" :show-overflow-tooltip="true"/>
        <el-table-column label="付款方式" align="center" prop="payWay">
          <template slot-scope="scope">
            <span v-if="scope.row.detailId && scope.row.payNo">权益+微信支付</span>
            <span v-else-if="scope.row.detailId||(scope.row.couponId&&!scope.row.payNo)">权益支付</span>
            <span v-else-if="scope.row.payNo">微信支付</span>
            <span v-else>免费</span>
          </template>
        </el-table-column>
        <el-table-column label="实付金额" align="center" prop="enrollCost" />
        <el-table-column label="付款单号" align="center" prop="payNo" :show-overflow-tooltip="true"/>
        <el-table-column label="权益消耗" align="center" prop="qy">
          <template slot-scope="scope">
            <span >{{ scope.row.detailId  ? scope.row.rightCount+"次":'0次' }}</span>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" v-show="false" />仅导入未登录小程序用户的营员数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listYppUser, getYppUser, delYppUser, addYppUser, updateYppUser, exportSelectedYppUser,exportYppUser,importTemplate } from "@/api/ypp/user";
import { listCouponInfo} from "@/api/ypp/couponInfo";
import { listQyk } from "@/api/wx/qyk";
import { addDetail } from "@/api/wx/detail";
import { addCouponDetail} from "@/api/ypp/couponDetail";
import { listSnpEnroll } from "../../../api/ypp/enroll";
import {getToken} from "@/utils/auth";
export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 活动报名表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dataType:0,
        wxUserId: undefined,
        name: undefined,
        age: undefined,
        gender: undefined,
        grade: undefined,
        phone: undefined,
        identityNumber: undefined,
        region: undefined,
        address: undefined,
        parentName:undefined,
        c:0,
        orderByName:'c'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      cardOptions:[],
      //活动参与记录
      attendList:[],
      enrollShow:false,
      couponInfoList:[],
      qykList:[],
      userId:undefined,
      couponShow:false,
      couponForm:{
        userId:undefined,
        couponId:undefined
      },
      cardShow:false,
      cardForm:{
        userId:undefined,
        qykId:undefined
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ypp/user/importData"
      },
    };
  },
  created(e) {
    if(this.$route.query.id){
      this.queryParams.wxUserId = this.$route.query.id;
    }
    this.getList();
    this.getDicts("card_type").then(response => {
      this.cardOptions = response.data;
    });
    this.getOption();
  },
  methods: {
    getOption(){
      listCouponInfo({status:1,lyfs:1}).then(res=>{
        if(res.code == 200) {
          var list = [];
          var date = new Date();
          res.rows.forEach(function (value) {
            if(!value.yxts){
              var yxsj = new Date(value.yxsj);
              if (yxsj < date) {
                value.disabled = true;
              }
            }
            list.push(value);

          });
          this.couponInfoList = list;
        }
      });
      listQyk().then(res=>{
        if(res.code == 200){
          var list = [];
          var date = new Date();
          res.rows.forEach(function (value) {
              var yxsj = new Date(value.expiration);
              if (yxsj < date) {
                value.disabled = true;
              }
            list.push(value);

          });
          this.qykList = list;
        }
      })
    },
    sendCoupon(row){
      this.couponForm={
        userId:undefined,
        couponId:undefined
      };

      this.userId = row.id;
      this.couponShow = true;
    },
    checkCoupon(row){
      var location = '/zx/coupon/record?userName='+row.name;
      this.$router.push({'path':location})
    },
    submitCouponForm(){
      this.couponForm.userId = this.userId;
      if(!this.couponForm.userId){
        this.$message.error("请选择营员");
        return ;
      }
      if(!this.couponForm.couponId){
        this.$message.error("请选择优惠券");
        return ;
      }
      addCouponDetail(this.couponForm).then(res=>{
        if(res.code == 200){
          this.$message.success("添加成功");
          this.couponShow = false;
        }
      })
    },

    sendCard(row){
      this.cardForm={
        userId:undefined,
        qykId:undefined
      };

      this.userId = row.id;
      this.cardShow = true;
    },
    submitCardForm(){
      console.log(this.cardForm)
      this.cardForm.userId = this.userId;
      if(!this.cardForm.userId){
        this.$message.error("请选择营员");
        return ;
      }
      if(!this.cardForm.qykId){
        this.$message.error("请选择权益卡");
        return ;
      }
      addDetail(this.cardForm).then(res=>{
        if(res.code == 200){
          this.$message.success("添加成功");
          this.cardShow = false;
        }
      })
    },
    /** 查询活动报名列表 */
    getList() {
      this.loading = true;
      listYppUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    showEnrolls(row){
      var that = this;
      that.enrollShow = true;
      const userId = row.id;
      var param = {
        userId:userId,
        status:100
      };
      listSnpEnroll(param).then(res=>{
        if(res.code == 200){
          that.attendList = res.rows;
        }
      })
    },
    //性别字典翻译
    genderFormat(row,column){
      if(row.gender == 0){
        return "未知";
      }else if(row.gender == 1){
        return  "男";
      }else if(row.gender == 2){
        return "女";
      }
    },
    // 状态字典翻译
    cardFormat(row, column) {
      return this.selectDictLabel(this.cardOptions, row.idType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        wxUserId: undefined,
        name: undefined,
        age: undefined,
        gender: undefined,
        grade: undefined,
        phone: undefined,
        identityNumber: undefined,
        region: undefined,
        address: undefined,
        parentName:undefined,
        account:undefined,
        school:undefined,
        c:0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加活动报名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getYppUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改使用人";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateYppUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addYppUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除使用人编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delYppUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      const ids = row.id || this.ids;
      if(ids&&ids.length>0){
        this.$confirm('是否确认导出选中的活动报名数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSelectedYppUser(ids);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }else {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有使用人数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportYppUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style scoped>
 .jc{
   display: flex;
   justify-content: center;
 }
</style>
